package com.example.cloudmusic.home.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.cloudmusic.databinding.ItemMusicTypeBinding
import com.example.cloudmusic.home.model.MusicStyle

/**
 * 音乐风格适配器
 */
class MusicStyleAdapter : BaseListAdapter<MusicStyle, MusicStyleAdapter.ViewHolder>(MusicStyleDiffCallback()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        return ViewHolder(
            ItemMusicTypeBinding.inflate(
                LayoutInflater.from(parent.context), parent, false
            )
        )
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(getItem(position))
    }

    inner class ViewHolder(private val binding: ItemMusicTypeBinding) :
        RecyclerView.ViewHolder(binding.root) {

        init {
            binding.root.setOnClickListener { onItemClick(adapterPosition) }
        }

        fun bind(item: MusicStyle) {
            binding.apply {
                cmMusicTypeType.text = item.style

                Glide.with(root)
                    .load(item.imageUrl)
                    .into(cmMusicTypeImg)
            }
        }
    }

    private class MusicStyleDiffCallback : DiffUtil.ItemCallback<MusicStyle>() {
        override fun areItemsTheSame(oldItem: MusicStyle, newItem: MusicStyle): Boolean =
            //TODO id
            oldItem.style == newItem.style

        override fun areContentsTheSame(oldItem: MusicStyle, newItem: MusicStyle): Boolean =
            oldItem.style == newItem.style &&
                    oldItem.imageUrl == newItem.imageUrl
    }
}